function onLoad() {
	reloadTabs();
	chrome.tabs.onCreated.addListener(function(tabs) {
		addTabListener(tabs);
	});
	chrome.tabs.onRemoved.addListener(function(tabsId, removeInfo) {
		rmTabListener(tabsId, removeInfo);
	});
	
	chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
		updateTabListener(tabId, changeInfo, tab);
	});
};

function addTab() {
	var createProperties = new Object();
	createProperties.active = false;
	createProperties.pinned = true;
	chrome.tabs.create(createProperties);
}

function rmTab(tabId) {
	chrome.tabs.remove(tabId);
}

function addDiv(tab) {
	if(tab.url == "chrome-extension://ggafgehibkijggibfaddkhghimofiebg/main.html") {
		//do something
	} else {
		
		var index 	= tab.index + 1;
		var tabBar = document.getElementById('tabBar');
		var newDiv = document.createElement('div');
		var divID = tab.id;
		var divName = 'test';
		
		newDiv.setAttribute('id', divID);
		newDiv.setAttribute('name', divName);
		newDiv.setAttribute('class', 'tabBarItem');
		newDiv.innerHTML = '<div style="float:left; width:18px;"><img src="' + tab.favIconUrl + '"></div><a href="' + tab.url + '" 					    target="contentFrame"><div style="float:left; width:85%; text-overflow: ellipsis;  overflow: hidden; white-space: 				    nowrap;">(' + index + ')&nbsp;' + tab.title + '</div></a><div style="float:right;" onclick="javascript:rmTab(' + tab.id + ')"><img src="' + cvt.dirs.img + 'close.png"></div>';
		tabBar.appendChild(newDiv);
	}
}

//TODO: remove all tabs from div
function clearTabs() {
	var tabBar = document.getElementById('tabBar');
//   for(var i = 1; i < 
	var tabBar_tab = document.getElementsByName('test');
	console.log(tabBar_tab.length);
		
}
//TODO

function reloadTabs() {
	chrome.tabs.query({}, function(tabs) { 
		for(var i = 0; i < tabs.length; i++) {
			addDiv(tabs[i]);
		}
	});   
}

function addTabListener(tab) {
	addDiv(tab);
}

function rmTabListener(tabId, removeInfo) {
	var tabBar 	   = document.getElementById('tabBar');
	var tabBar_tabId = document.getElementById(tabId); 
	tabBar.removeChild(tabBar_tabId);
}

function updateTabListener(tabId, changeInfo, tab) {
	if(tab.url == "chrome-extension://ggafgehibkijggibfaddkhghimofiebg/main.html") {
		//do something
	} else {
		var tabBar = document.getElementById('tabBar');
		var tabBar_tabId = document.getElementById(tabId);
		var index = tab.index + 1;
		tabBar_tabId.innerHTML = '<div style="float:left; width:18px;"><img src="' + tab.favIconUrl + '"></div><a href="' + tab.url + '" 					    target="contentFrame"><div style="float:left; width:85%; text-overflow: ellipsis;  overflow: hidden; white-space: 				    nowrap;">(' + index + ')&nbsp;' + tab.title + '</div></a><div style="float:right;"><a href="javascript:rmTab(' + tab.id + ')"><img 				    src="' + cvt.dirs.img + 'close.png"></a></div>';
	}
}
